﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.Web.SessionState;
using System.Data;
using System.IO;

using Newtonsoft.Json;
using Framework.DataAccess;
using Framework.Common.JsonEntities;
using Framework.Common;
using Framework.Common.Common;
using Mode;

namespace WebSite.WebServer
{
    /// <summary>
    /// RoleMange 的摘要说明
    /// </summary>
    public class RoleMange : IHttpHandler, IRequiresSessionState
    {

        JsonReturnMessages msg;
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            msg = new JsonReturnMessages();
            try
            {
                string action = context.Request.Params["Action"];
                if (action == "AreaRoleList")
                    AreaRoleList();
                if (action == "RoleList")
                    RoleList();
                if (action == "SaveRoleItem")
                    SaveRoleItem();
                if (action == "FenRoleAndRole")
                    FenRoleAndRole();
                if (action == "SaveRole")
                    SaveRole();
                if (action == "stopItem")
                    stopItem();
                if (action == "Super")
                    PromotePower();
               
            }
            catch (Exception err)
            {
                var message = err.Message;
                if (err.InnerException != null && err.InnerException.Message != null)
                    message += "<BR>" + err.InnerException.Message;

                msg.IsSuccess = 0;
                msg.Msg = message;

                var json = JsonConvert.SerializeObject(msg);
                context.Response.Write(json);
            }

            context.Response.End();
        }

        /// <summary>
        /// 停用 启用
        /// </summary>
        void stopItem()
        {
            var context = System.Web.HttpContext.Current;
            loginInfo lu = chklogin();
            if (lu != null)
            {
                msg.IsSuccess = 0;
                if (lu.R_POWER == 1)
                {
                    int staus = context.Request.Params["stas"].ToInt();
                    int jid = context.Request.Params["jid"].ToInt();
                    role myrle = new role();
                    if (myrle.stopItem(staus, jid) > 0)
                    {
                        msg.IsSuccess = 1;

                    }
                    else
                    {
                        msg.Msg = "保存失败！";
                    }


                }
                else
                {
                    msg.Msg = "你没权限操作！";
                }
            }
            context.Response.Write(JsonConvert.SerializeObject(msg));
        }

        void SaveRole()
        {
            var context = System.Web.HttpContext.Current;
            loginInfo lu = chklogin();
            if (lu != null)
            {

                msg.IsSuccess = 0;
                if (lu.R_POWER == 1)
                { 
                    int areid =context.Request.Params["arid"].ToInt();
                    string data = context.Request.Params["data"];
                    if (data != "")
                    {
                       data= data.TrimEnd(',');
                       string[] mm = data.Split(',');
                       role myrole = new role();
                       if (myrole.AddAreaRole(areid, mm) >0)
                       {
                           msg.IsSuccess = 1;
                       }
                       else
                           msg.Msg = "保存失败";
                    
                    }else
                        msg.Msg = "保存失败";
                
                   
                }
                else
                {
                    msg.Msg = "你没权限操作！";
                }
            }

            context.Response.Write(JsonConvert.SerializeObject(msg));
        }

        /// <summary>
        /// 
        /// </summary>
        void FenRoleAndRole()
        {
            var context = System.Web.HttpContext.Current;
            loginInfo lu = chklogin();
          
           
            if (lu != null)
            {

                int arid = context.Request.Params["areaid"].ToInt();

                List<JsonComboBox> items = new List<JsonComboBox>();
                List<JsonComboBox> items2 = new List<JsonComboBox>();

                DataView dv = new User().GetTheDepartmentList(arid,lu.R_POWER);
               
               
                role myrole = new role();
                 IList<role_tableEx> Rdata =new List<role_tableEx>();
                IList<role_table> rll = myrole.GetRolistALL(true);
                if (rll != null)
                {
                    foreach (role_table Item in rll)
                    {
                        JsonComboBox dd = new JsonComboBox();
                        role_tableEx rr =new role_tableEx();
                        dd.id = Item.id.ToString();
                        dd.text = Item.name;
                        rr.id =Item.id;
                        rr.name =Item.name;
                        rr.issslect =0;
                         if (dv != null)
                         {
                             for (int i = 0; i < dv.Count; i++)
                             {
                                 if (dd.id == dv[i]["id"].ToStr()) {
                                     rr.issslect = 1;
                                 }   
                             }
                         }
                        Rdata.Add(rr);
                       
                    }
                }

                var adata = new { data = Rdata };

                context.Response.Write(JsonConvert.SerializeObject(adata));

            }else
                context.Response.Write("[{\"data\":[]}]");
        
        }

        /// <summary>
        /// 提权
        /// </summary>
        void PromotePower()
        {
            var context = System.Web.HttpContext.Current;
            loginInfo lu = chklogin();
            if (lu != null)
            {
                int memberid = context.Request.Params["memberid"].ToInt();
                role r  = new role();
                try{
                    r.PromotePower(memberid);
                    msg.IsSuccess = 1;
                    msg.Msg = "提权成功.";
                }catch(Exception ex)
                {
                    msg.IsSuccess = 0;
                    msg.Msg = ex.Message;
                }
                context.Response.Write(JsonConvert.SerializeObject(msg));
            }
        }

        #region
        void SaveRoleItem() {
            var context = System.Web.HttpContext.Current;
            loginInfo lu = chklogin();
            if (lu != null)
            {

                msg.IsSuccess = 0;
                if (lu.R_POWER == 1 && lu.A_LEVEL ==0 )
                {
                    string name = context.Request.Params["name"];
                    string rmark = context.Request.Params["rmark"];
                    if (name.Trim() != "")
                    {
                        try
                        {

                            role myrole = new role();
                            int R = myrole.AddRoleNew(name, rmark);

                            msg.IsSuccess = R;
                            msg.Msg = "";
                            if (R == -1)
                                msg.Msg = "添加失败";

                        }
                        catch (Exception er)
                        {
                            msg.Msg = er.Message;
                        }
                    }
                    else
                    {
                        msg.Msg = "名称不能为空";
                    }
                }
                else
                {
                    msg.Msg = "操作受限.";
                }

            }
            context.Response.Write(JsonConvert.SerializeObject(msg));
        }
        #endregion
        #region
        void RoleList()
        {
            var context = System.Web.HttpContext.Current;
            loginInfo lu = chklogin();
            List<JsonComboBox> items = new List<JsonComboBox>();
            if (lu != null)
            {
            

                role myrole = new role();

               IList<role_table> rll= myrole.GetRolistALL(true);

               if (rll != null)
                {
                   foreach(role_table Item in rll)
                    {
                        JsonComboBox dd = new JsonComboBox();
                        dd.id = Item.id.ToString();
                        dd.text = Item.name;
                      
                        items.Add(dd);
                    }
                }
            }
            context.Response.Write(JsonConvert.SerializeObject(items));
        }
        #endregion

        #region
        void AreaRoleList()
        {
            var context = System.Web.HttpContext.Current;
            loginInfo lu = chklogin();
            if (lu != null)
            {

                role myRole = new role();

                int areid = context.Request.Params["aid"].ToInt();
                int status = context.Request.Params["status"].ToInt();
                string rolename = context.Request.Params["roleName"];

                PageView pageInfo = new PageView();
                pageInfo.PageIndex = context.Request.Params["page"].ToInt(1);
                pageInfo.PageSize = context.Request.Params["pagesize"].ToInt(20);
                pageInfo.SortName = context.Request.Params["sortname"].ToStr();
                pageInfo.SortOrder = context.Request.Params["sortorder"].ToStr();
                pageInfo.SearchParams = context.Request.Params;


                PageList<object> List = myRole.GetRolist(areid,status, rolename, pageInfo);


                string Rjson = @"{""Rows"":null,""Total"":""0""}";
                if (List.Data != null)
                {
                    Rjson = @"{""Rows"":" + List.Data.ToJson() + @",""Total"":""" + List.Total + @"""}";
                }


                context.Response.Write(Rjson);
            }
        }
        #endregion

        loginInfo chklogin()
        {
            try
            {
                return SessionShard.loginUser;
            }
            catch
            {
                msg.IsSuccess = -9;
                msg.Msg = "登陆失效，请重新登陆!";
                return null;
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}